
const { log } = require('console');
const net = require('net');
const process = require('process');
const {plc_socket_list} = require('../config.json');
const mainThrad = require('../index');
class Client {

    quitting = false
    conn = null
    retryTimeout = 1000
    retriedTimes
    maxRetrieds = 5
    port = null
    ip = ''

    constructor (port, ip) {
        this.port = port;
        this.ip = ip;
        process.stdin.resume();
        process.stdin.on('data', (data) => {
            if(data.toString().trim().toLowerCase() === 'quit'){
                this.quitting = true;
                this.conn.end();
                process.stdin.pause()
            }
        });

        this.conn = net.createConnection(this.port, this.ip, () => {
            this.retriedTimes = 0;
            console.log('连接成功');
            setInterval(() => {
                this.conn.write('500000FF03FF000018001004010000D*020100001B');
            }, 1000)
        })

        this.conn.on('error', (err) => {
            console.error('错误:' + err.message);
        });

        this.conn.on('close', () => {
            if(!this.quitting){
                console.log('重新连接');
                this.reconnect();
            } else {
                console.log('终止连接');
            }
        })

        this.conn.on('data', (data) => {
            // data构成： 头 + 长度 + 0000 + panelID(10字 --》2个字符， 4个hex编码单元) + lotId (16字) + 米数字 （1字）
            let buf = Buffer.from(data.toString(), 'hex');
            let bufstr = buf.slice(11, 31).toString();
            mainThrad.getPlcData({port: this.port, panelId: bufstr});
        })
    }
    /**
     * 重连
     */
    reconnect () {
		if(this.retriedTimes > this.maxRetrieds){
			throw new Error('重连次数超过最大值', this.maxRetrieds);
		} else {
			this.retriedTimes += 1;
			setTimeout(() => {
                new Client(this.port, this.ip);
            }, this.retryTimeout);
		}
	}
    /**
     * 获取所有PLC
     * @returns
     */
    static getAllInstance () {
        return plc_socket_list.map(item => {
            return new Client(item.port, item.ip);
        })
    }
}

module.exports = Client;